<template>
  <div class="app-container">
    <template v-if="!addArticleShow">
      <div class="search-bar">
        <el-form ref="queryFor" :model="queryParams" :inline="true">
          <el-form-item label="适用场景" prop="name">
            <el-select
              v-model="queryParams.type"
              placeholder="请选择"
              style="width: 200px"
              clearable
            >
              <el-option
                v-for="(item, index) in VOUCHER_TYPE_ENUM"
                :key="index"
                :label="item.label"
                :value="item.id"
                style="width: 200px"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布时间">
            <el-date-picker
              v-model="tempTime"
              :editable="false"
              type="datetimerange"
              range-separator="~"
              start-placeholder="开始时间"
              end-placeholder="截止时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="handleChange"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <template #icon>
                <Search />
              </template>
              搜索
            </el-button>
            <el-button @click="handleResetQuery">
              <template #icon>
                <Refresh />
              </template>
              重置
            </el-button>
            <el-button type="primary" @click="handleAdd('add')">
              <template #icon>
                <Setting />
              </template>
              新增配置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-tabs v-model="queryParams.status" class="enter-tabs" @tab-change="handleClick">
        <el-tab-pane label="全部" name=""></el-tab-pane>
        <el-tab-pane label="待发布" :name="1"></el-tab-pane>
        <el-tab-pane label="已上架" :name="2"></el-tab-pane>
        <el-tab-pane label="已下架" :name="3"></el-tab-pane>
      </el-tabs>
      <BasePageTable
        :table-data="tableData"
        :table-columns-data="tableColumnsData"
        :total="total"
        :loading="loading"
        :page-num="queryParams.pageNum"
        :page-size="queryParams.pageSize"
        @handleQuery="changePage"
      >
        <template #type="{ row, name }">
          {{ row.name }}
          <span v-if="row.supportedCategoryName">-</span>
          {{ row.supportedCategoryName }}
          <!-- {{ VOUCHER_TYPE_ENUM_JSON[row.type] }} -->
        </template>
        <template #supportedMerchant="{ row, name }">
          <span
            v-for="item in row.supportedMerchant"
            :key="item.companyId"
            style="margin-right: 10px"
          >
            {{ item.companyName }}
          </span>
        </template>
        <template #effectiveValue="{ row, name }">
          {{ effectiveTime(row) }}
        </template>
        <template #enable="{ row, name }">
          <el-switch
            v-model="row.enable"
            inline-prompt
            active-text="启用"
            inactive-text="禁用"
            :active-value="1"
            :inactive-value="2"
            :before-change="() => enableCoupon(row)"
          />
        </template>
        <template #status="{ row, name }">
          <el-tag :type="tagStatus[row.status]">{{ VOUCHER_STATE_ENUM[row.status] }}</el-tag>
        </template>
        <template #operation="{ row, name }">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleEdit(row, 'edit')"
            :disabled="row.status !== 1"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            icon="DeleteFilled"
            @click="handleEdit(row, 'del')"
            :disabled="row.status != 1"
          >
            删除
          </el-button>
          <el-button
            link
            type="danger"
            icon="Edit"
            v-if="row.status == 2"
            @click="handleEdit(row, 'grounding')"
            :disabled="row.status == 0"
          >
            下架
          </el-button>
          <el-button
            link
            type="success"
            icon="Edit"
            v-if="row.status == 3"
            @click="handleEdit(row, 'putaway')"
            :disabled="row.status == 0"
          >
            上架
          </el-button>
          <el-button link type="primary" @click="handleEdit(row, 'look')">查看详情</el-button>
        </template>
      </BasePageTable>
    </template>
    <template v-else>
      <AddVoucher
        ref="addVoucherRe"
        @backTo="handleBackTo"
        :couponData="detailData"
        :type="showType"
        v-if="showType != 'look'"
      ></AddVoucher>
      <couponDetail @backTo="detailBackTo" :couponData="detailData" v-else></couponDetail>
    </template>
  </div>
</template>
<script setup>
import AddVoucher from "../components/addVoucher/index.vue";
import couponDetail from "../components/couponDetail/index.vue";
import listApi from "@/api/coupon/couponList";
import {
  VOUCHER_TYPE_ENUM,
  VOUCHER_TYPE_ENUM_JSON,
  VOUCHER_STATE_ENUM,
} from "@/enums/coupon/coupon";

const queryParams = reactive({
  type: null,
  pageNum: 1,
  pageSize: 10,
  status: "",
  publishBeginTime: "",
  publishEndTime: "",
});
const tagStatus = ref({
  1: "info",
  2: "success",
  3: "warning",
});
const detailData = ref({});
const total = ref(0);
const tableData = ref([]);
const addArticleShow = ref(false);
const loading = ref(false);
const showType = ref("edit");
const tempTime = ref();
const tableColumnsData = ref([
  {
    prop: "type",
    label: "名称",
    showOverflowTooltip: true,
    customSlot: "type",
  },
  {
    prop: "amount",
    label: "券额",
    showOverflowTooltip: true,
  },
  // {
  //   prop: "supportedMerchant",
  //   label: "适用场景",
  //   showOverflowTooltip: true,
  //   customSlot: "supportedMerchant",
  // },
  {
    prop: "effectiveValue",
    label: "有效日期",
    showOverflowTooltip: true,
    customSlot: "effectiveValue",
  },
  {
    prop: "createTime",
    label: "创建时间",
    showOverflowTooltip: true,
  },
  {
    prop: "status",
    label: "状态",
    showOverflowTooltip: true,
    customSlot: "status",
  },
  {
    prop: "overlayCount",
    label: "叠加规则",
    showOverflowTooltip: true,
  },
  {
    prop: "storageCount",
    label: "剩余数量",
    showOverflowTooltip: true,
  },

  {
    prop: "enable",
    label: "启用状态",
    showOverflowTooltip: true,
    customSlot: "enable",
  },
  {
    prop: "publishTime",
    label: "发布时间",
    showOverflowTooltip: true,
  },
  {
    prop: "operation",
    label: "操作",
    width: 300,
    align: "center",
    fixed: "right",
    customSlot: "operation", // 自定义插槽名称
  },
]);

function handleSearch() {
  queryParams.pageNum = 1;
  getList();
}
// 重置查询
function handleResetQuery() {
  queryParams.pageNum = 1;
  queryParams.type = null;
  queryParams.publishBeginTime = "";
  queryParams.publishEndTime = "";
  tempTime.value = "";
  getList();
}
function handleAdd(type) {
  addArticleShow.value = true;
  detailData.value = {};
  showType.value = type;
}
const detailBackTo = () => {
  addArticleShow.value = false;
  getList();
};
function changePage(val) {
  queryParams.pageNum = val.pageNum;
  queryParams.pageSize = val.pageSize;
  getList();
}
const handleBackTo = () => {
  addArticleShow.value = false;
  getList();
};
function effectiveTime(row) {
  if (row.effectiveType === 1) {
    if (row.effectiveValue.day == -1) {
      return "长期有效";
    } else {
      return row.effectiveValue.day + "天";
    }
  } else {
    return row.effectiveValue.begin + "~" + row.effectiveValue.end;
  }
}
// 查询
function getList() {
  console.log(11111);
  console.log(queryParams);
  loading.value = true;
  listApi
    .list(queryParams)
    .then((data) => {
      tableData.value = data.list || [];
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}
function enableCoupon(row) {
  loading.value = true;
  let params = {
    id: row.id,
    enable: row.enable == 2 ? 1 : 2,
  };
  try {
    listApi
      .changeEnable(params)
      .then((res) => {})
      .finally(() => {
        getList();
      });
  } catch (err) {
    row.enable = row.enable == 1 ? 2 : 1;
  }
}
function handleClick(data) {
  handleSearch();
}

function handleChange(val) {
  if (val) {
    const [startTime, endTime] = val;
    queryParams.publishBeginTime = startTime;
    queryParams.publishEndTime = endTime;
  } else {
    queryParams.publishBeginTime = "";
    queryParams.publishEndTime = "";
  }
}

function handleEdit(row, type) {
  if (type == "look" || type == "edit") {
    showType.value = type;
    loading.value = true;
    listApi
      .detail(row.id)
      .then((res) => {
        detailData.value = res;
        addArticleShow.value = true;
      })
      .finally(() => {
        loading.value = false;
      });
  } else if (type == "del") {
    ElMessageBox.confirm("确定删除？", "提示", { type: "warning" }).then(() => {
      let data = {
        id: row.id,
      };
      loading.value = true;
      listApi
        .delCoupon(data)
        .then(() => {
          getList();
          ElMessage.success("删除成功");
        })
        .finally(() => {
          loading.value = false;
        });
    });
  } else if (type == "grounding") {
    ElMessageBox.confirm("确定下架吗？", "提示", { type: "warning" }).then(() => {
      let data = {
        id: row.id,
        status: 3,
      };
      loading.value = true;
      listApi
        .changeStatus(data)
        .then(() => {
          getList();
          ElMessage.success("下架成功");
        })
        .finally(() => {
          loading.value = false;
        });
    });
  } else if (type == "putaway") {
    ElMessageBox.confirm("确定上架吗？", "提示", { type: "warning" }).then(() => {
      let data = {
        id: row.id,
        status: 2,
      };
      loading.value = true;
      listApi
        .changeStatus(data)
        .then(() => {
          getList();
          ElMessage.success("上架成功");
        })
        .finally(() => {
          loading.value = false;
        });
    });
  }
}
onMounted(async () => {
  getList();
});
</script>
